﻿// ===============================================================================
// XCI.NET 西安交通信息WinForm开发框架 2018 版权所有
// ===============================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using XCI.Config;
using XCI.Data.Provider;
using XCI.Logger;

namespace XCI.Data
{
    /// <summary>
    /// 数据库工厂管理类
    /// </summary>
    public static class DatabaseFactory
    {
        /// <summary>
        /// 实例管理器
        /// </summary>
        private static readonly Dictionary<string, IDbProvider> providerFactory =
            new Dictionary<string, IDbProvider>();

        /// <summary>
        /// 日志接口
        /// </summary>
        private static ILogger logger;

        /// <summary>
        /// 初始化数据库工厂管理类
        /// </summary>
        static DatabaseFactory()
        {
            providerFactory.Add("sqlserver", new SQLServerProvider());
            providerFactory.Add("oracle", new OracleProvider());
            providerFactory.Add("mysql", new MySQLProvider());
            providerFactory.Add("sqlite", new SQLiteProvider());
        }

        /// <summary>
        /// 日志接口
        /// </summary>
        public static ILogger Logger
        {
            get => logger ?? (logger = LoggerFactory.Default);
            set => logger = value;
        }

        /// <summary>
        /// 获取数据库配置
        /// </summary>
        /// <param name="name">数据库配置名称(如果为空,返回第一个配置项)</param>
        /// <returns>返回指定名称的日志数据库配置信息</returns>
        public static DatabaseSetting GetSetting(string name = null)
        {
            var settings = ConfigFactory.Default.Get("Database", () => new List<DatabaseSetting>());
            return string.IsNullOrWhiteSpace(name) ? settings.FirstOrDefault() : settings.FirstOrDefault(p => p.Name.Equals(name));
        }

        /// <summary>
        /// 注册数据库实现类
        /// </summary>
        /// <param name="name">数据库类型名称</param>
        /// <param name="provider">数据库实现</param>
        public static void SetProvider(string name, IDbProvider provider)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentNullException(name, "数据库类型名称不能为空");
            }

            providerFactory.Add(name, provider);
        }

        /// <summary>
        /// 获取数据库实现类
        /// </summary>
        /// <param name="name">数据库类型名称</param>
        /// <returns>返回数据库实现</returns>
        public static IDbProvider GetProvider(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return providerFactory["sqlserver"];
            }

            return providerFactory[name];
        }
    }
}